<%@page import="QRCG.Util"%>
<%@page import="java.util.*"%>
<%@page import="QRCG.DatabaseManager"%>
<%@page import="java.text.*"%>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Game Information</title>
<link href="index.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="jquery.accordion.js"></script>
<script type="text/javascript" src="jquery.rating.js"></script>
<script type="text/javascript">
	$(document).ready(function(){
		jQuery('#list1b').accordion({
			autoheight: false
		});
		$('.rating_radio').rating({split:2, maxvalue:5, increment:.5});
		$('.rating_radio').rating('readOnly');
	});
</script>
<script language="javascript">
	function popup(url) {
		var win_dow = window.open(url, 'myPopUp',
				"type=fullWindow, fullscreen, scrollbars=yes");
	}
</script>
<script language="javascript">
	  function playTheGame(gameId) {
		window.location =  "PlayGame.jsp?game_id=" + gameId;
      }
</script>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
    
      // Load the Visualization API and the barchart package.
      google.load('visualization', '1.0', {'packages':['corechart']});
      
      // Set a callback to run when the Google Visualization API is loaded.
      google.setOnLoadCallback(drawChart);
      
      // Callback that creates and populates a data table, 
      // instantiates the pie chart, passes in the data and
      // draws it.
      function drawChart() {

      // Create the data table.
      var data = new google.visualization.DataTable();      
      data.addColumn('string', 'Level');
      data.addColumn('number', '# of Players Complete this');
      
      <%
      	String gameId = request.getParameter("game_id");
		
  		DatabaseManager connection = new DatabaseManager();
  		connection.connect();
      	
  		for (HashMap<String, Object> row : connection.getNumPlayersFinishedLevels(gameId)) {
			%>
			data.addRow(['Level <%=row.get("level_id").toString()%>',<%=row.get("player_count").toString()%>]);
  			<%
		}
      %>
      data.addRow(['All Levels',<%=connection.getNumPLayersFinishedGame(gameId)%>]);
      // Set chart options
      var options = {'title':'Game Statistics',
    		  		vAxis: {title: 'Level',  titleTextStyle: {color: 'red'}},
    		  		hAxis: {title: '# of Players',  titleTextStyle: {color: 'red'}, viewWindowMode:'explicit', viewWindow: {min: 0}, baselineColor: 'black', minValue: 0},
    		  		'backgroundColor':'gainsboro',
                    'width':400,
                    'height':300};

      // Instantiate and draw our chart, passing in some options.
      var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
    </script>
</head>

<%@ include file="header.jsp"%>

<body>
	<%
	//this connection moved a little top of the code. because it is necessary to connect to database to draw a statistics chart.
	//String gameId = request.getParameter("game_id");	
	//DatabaseManager connection = new DatabaseManager();
	//connection.connect();
	
	String game_name = connection.getGameInformation(DatabaseManager.GameInformation.NAME, gameId);
	
	ArrayList<HashMap<String, Object>> levels = new ArrayList<HashMap<String, Object>>();
	levels = connection.getAllLevelsOfGame(gameId); //all levels of the game to be viewed
	
	String creator_id  = connection.getGameInformation(DatabaseManager.GameInformation.CREATOR_ID, gameId);
	String desc     = connection.getGameInformation(DatabaseManager.GameInformation.DESCRIPTION, gameId);
	String begin_date = connection.getGameInformation(DatabaseManager.GameInformation.BEGIN_DATE, gameId);
	String end_date   = connection.getGameInformation(DatabaseManager.GameInformation.END_DATE, gameId);
	String location = connection.getGameInformation(DatabaseManager.GameInformation.LOCATION, gameId);
	String ratingStr = connection.getGameInformation(DatabaseManager.GameInformation.RATING, gameId);
	float rating = 0;
	if(Util.hasTextContent(ratingStr)){
		try{
			rating = Float.parseFloat(ratingStr);
		}catch(NumberFormatException e){
			rating = 0;
		}
	}
	String creator_nickname = connection.get_nicknamefrom_id(creator_id);
	String user_nickname = (String) session.getAttribute("nickname");// Here, instead of nickname, user_nickname used to prevent duplications
	String gameinfo = "";
	String url ="";
	ArrayList<HashMap<String, Object>> games = new ArrayList<HashMap<String, Object>>();
	boolean owner = connection.userOwnsTheGame(user_nickname,gameId); //if the user is the owner of the game it's true
	boolean registered = connection.isUserRegisteredToGame(user_nickname, gameId); //if the user has registered to the game it's true
	boolean finished = connection.isGameFinished(gameId, nickname); //if the user has finished the game it's true
	boolean gameDateExpired = connection.gameDateExpired(gameId); //if the game's end date is passed it is true
	
	float userRating = connection.getRatingByUser(gameId, user_nickname);
	
	String creator = "";
	if(owner)
		creator = "You";
	else
		creator = creator_nickname;
%>
	<div id="page">
		<div id="page-bgtop">
			<div id="page-bgbtm">
				<div id="content" style="height: auto !important;">
					<div id="game-name">
						<%=game_name%>
					</div>
					<div id="game-creator-rating">
						<div id="game-creator-rating-text"><div style="text-align: right;">Created by <%=creator%></div> <div style="text-align: left;">Overall Rating:</div> </div>
						<input type="radio" class="rating_radio" <%=(rating>0.0 && rating<=0.5) ? "checked" : ""%> /> 
						<input type="radio" class="rating_radio" <%=(rating>0.5 && rating<=1.0) ? "checked" : ""%> />
						<input type="radio" class="rating_radio" <%=(rating>1.0 && rating<=1.5) ? "checked" : ""%> /> 
						<input type="radio" class="rating_radio" <%=(rating>1.5 && rating<=2.0) ? "checked" : ""%> />
						<input type="radio" class="rating_radio" <%=(rating>2.0 && rating<=2.5) ? "checked" : ""%> />
						<input type="radio" class="rating_radio" <%=(rating>2.5 && rating<=3.0) ? "checked" : ""%> /> 
						<input type="radio" class="rating_radio" <%=(rating>3.0 && rating<=3.5) ? "checked" : ""%> />
						<input type="radio" class="rating_radio" <%=(rating>3.5 && rating<=4.0) ? "checked" : ""%> /> 
						<input type="radio" class="rating_radio" <%=(rating>4.0 && rating<=4.5) ? "checked" : ""%> />
						<input type="radio" class="rating_radio" <%=(rating>4.5 && rating<=5.0) ? "checked" : ""%> />
					</div>
					
					<div id="game-description">
						<p><%=desc%></p>
					</div>
					<br/> <br/> <br/>
					<br/>
					
					<div id="game-information">	<% 
							if(Util.hasTextContent(user_nickname)) {
								if(owner) {  //user is the owner of the game
									request.setAttribute("message", "\n\n <b>Note:</b> You are the owner of the game, so you <u><b>can't</b></u> play it! \n");
									%>	${message} <br/><br/>
									<p style="text-align: center;font-size: x-large;"><b><u>Game Information</u></b></p> <%
									if (!levels.isEmpty()) {
										%>	
										
									<form action="ViewTheGameServe" method="post">
											<p style="padding-top: 10 px;">
											<b>Game takes place in: </b>
											<%=location%></p>
											<p><b>Number of levels: </b><%= levels.size() %></p> <%
											
// 									    String[] hintDescriptions = new String[levels.size()];
// 									    String[] hintKeywords = new String[levels.size()];
// 									    String[] hintCoordinates = new String[levels.size()];
// 									    String[] hintAddresses = new String[levels.size()];
										for (int i = 0; i < levels.size(); i++){
											HashMap<String, Object> mapLevels = (HashMap<String, Object>) levels.get(i);
// 											hintDescriptions[i] = (String)mapLevels.get("hint");
// 										    hintKeywords[i] = (String)mapLevels.get("level_code");
// 										    hintCoordinates[i] = (String)mapLevels.get("qr_address");
// 										    hintAddresses[i] = "";
										%>	<div id="level-description">
												<p><b><u>Level <%=i+1%></u></b></p>
												<p><b>Hint to players:</b> <%=mapLevels.get("hint")%></p>
												<p><b>Keyword for the Level:</b> <%=mapLevels.get("level_code")%></p>
												<p><b>Coordinates of the Level:</b>	<%=mapLevels.get("qr_address")%></p>
											</div>	
											
												<input name="hint_descriptions" type="hidden" value='<%=mapLevels.get("hint")%>'>
												<input name="hint_keywords" type="hidden" value='<%=mapLevels.get("level_code")%>'>
												<input name="hint_coordinates" type="hidden" value='<%=mapLevels.get("qr_address")%>'>
												<input name="hint_addresses" type="hidden" value="">
									<%
										}
									%>
<!-- 									<form action="ViewTheGameServe" method="post"> -->
										<input id="insert-button" type="submit" name="view_qr" value="QR Codes">
										<input name="game_id" type="hidden" value=<%=gameId%>>
									</form>
									<% }
								} else { //user is not owner of the game
									if(finished) {  //game is completed by the user
											request.setAttribute("message", "<u><b>Congratulations!</b></u> You have already finished this game!");
									} else { 		//game is not completed by the user
										if(gameDateExpired){ 	//end date of the game is passed. so game is not continuing.
											request.setAttribute("message", "<b>Note:</b> Sorry! This game's end date is expired, so you <u><b>can't</b></u> play it!");
										} else {		// ongoing game.
											%> 	<p style="padding-top: 10 px;">
											<b>This game is active until:</b>
											<%=end_date%>. <b>So, hurry up!</b> <br/> <%
											if(registered){	//user is registered to the game
												%>	<input id="insert-button" type="button" onClick="playTheGame(<%=gameId%>)" value="Play!">	<br/> 	<% 												
											} else {	//user is not registered to the game
											%>	<form action="ViewTheGameServe" method="post">
													<input id="insert-button" type="submit" name="register" value="Register">
													<input name="game_id" type="hidden" value=<%=gameId%>>
												</form>	<%
											}
										}
									}
									if(registered){  //whether the game is ongoing or not, user can vote this game.
									%>	<div>
											<form id="test" action="ViewTheGameServe" method="post">
												<input name="stars" type="radio" class="star" value=1 title="poor" <%=userRating==1 ? "checked" : ""%> /> 
												<input name="stars" type="radio" class="star" value=2 title="bad" <%=userRating==2 ? "checked" : ""%> />
												<input name="stars" type="radio" class="star" value=3 title="ok" <%=userRating==3 ? "checked" : ""%> /> 
												<input name="stars" type="radio" class="star" value=4 title="good" <%=userRating==4 ? "checked" : ""%> />
												<input name="stars" type="radio" class="star" value=5 title="very good" <%=userRating==5 ? "checked" : ""%> />
												&nbsp;&nbsp;
												<input id="vote-button" type="submit" name="vote" value="Vote">
												<input name="game_id" type="hidden" value=<%=gameId%>>
											</form>
										</div> 	<%
									}
								}
								if(!owner){
								%><br/> ${message} <br/>
									</p> <p style="text-align: center;font-size: x-large;"><b><u>Game Information</u></b></p> 
									<p style="padding-top: 10 px;">
									<b>Game takes place in: </b>
									<%=location%></p>
									<p><b>Number of levels: </b><%= levels.size() %></p><% 
								}
							}
						%>	</div>
							<p style="text-align: center;font-size: x-large;"><b><u>Statistics</u></b></p>
						<div style="clear: both;">&nbsp;</div>
						<!--Div that will hold the bar chart-->
    					<div id="chart_div"></div>
				</div>
				<!-- end #content -->
				<div id="sidebar">
					<ul>
						<li>
							<div style="clear: both;">&nbsp;</div>
						</li>
						<li>
							<h2>OTHER GAMES</h2>
						</li>
						
						<li>
							<div class="basic" id="list1b">

								<%
					games = connection.getOngoingGames();
					final int GAME_LIMIT=20;
					if (!games.isEmpty()) {
						for (int i = 0; i < games.size(); i++) {
							if(i>GAME_LIMIT)
								break;
							HashMap<String, Object> map1 = (HashMap<String, Object>) games.get(i);
							if(!map1.get("game_id").toString().equalsIgnoreCase(gameId)){
								url= "ViewTheGame.jsp?game_id=" + map1.get("game_id");
								
								gameinfo ="<b>Description:</b> " +(String)map1.get("description"); 
								gameinfo +="<br><b>Location:</b> ";
								gameinfo +=connection.getGameInformation(DatabaseManager.GameInformation.LOCATION, map1.get("game_id").toString());
						%>
								<a><%=map1.get("name")%></a>
								<div>
									<p><%=gameinfo %></p>
									<p style="cursor: pointer; color: red;"
										onclick="javascript:popup('<%=url%>')">Click here for more
										information</p>
								</div>

								<%} } } %>
							</div>
						</li>
					</ul>
				</div>
				<!-- end #sidebar -->
				<div style="clear: both;">&nbsp;</div>
			</div>
		</div>
	</div>

</body>
<script language="JavaScript1.2">

//Set delay before submenu disappears after mouse moves out of it (in milliseconds)
var delay_hide=5

/////No need to edit beyond here

var menuobj=document.getElementById? document.getElementById("onmouse") : document.all? document.all.describe : document.layers? document.dep1.document.dep2 : ""

function showit(which,sub){
clear_delayhide()
thecontent=(which==-1)? "" : sub
if (document.getElementById||document.all)
menuobj.innerHTML=thecontent
else if (document.layers){
menuobj.document.write(thecontent)
menuobj.document.close()
}
}

function resetit(e){
if (document.all&&!menuobj.contains(e.toElement))
delayhide=setTimeout("showit(-1,'')",delay_hide)
else if (document.getElementById&&e.currentTarget!= e.relatedTarget&& !contains_ns6(e.currentTarget, e.relatedTarget))
delayhide=setTimeout("showit(-1,'')",delay_hide)
}

function clear_delayhide(){
if (window.delayhide)
clearTimeout(delayhide)
}

function contains_ns6(a, b) {
while (b.parentNode)
if ((b = b.parentNode) == a)
return true;
return false;
}


</script>
<%@ include file="footer.jsp"%>